package com.twu.biblioteca;

import com.twu.biblioteca.libraryitems.Book;
import com.twu.biblioteca.libraryitems.LibraryItem;
import com.twu.biblioteca.libraryitems.Movie;

import java.util.ArrayList;
import java.util.List;
/**
 * Created by sarahc on 1/8/14.
 */
public class Library {

    private List<LibraryItem> libraryItems;
    private List<Customer> customers;

    public Library (List<Customer> customers, List<LibraryItem> libraryItems){
        this.libraryItems = libraryItems;
        this.customers = customers;
    }

    public void addItem(LibraryItem libraryItem){
        this.libraryItems.add(libraryItem);
    }

   public List<LibraryItem> getLibraryItems(){
       return this.libraryItems;
   }

    public boolean checkoutItem(Customer customer, LibraryItem libraryItem){
        if (!verifyCustomerAndItem(customer, libraryItem))
            return false;

        if (!customer.haveItems() && libraryItem.isAvailable()){
            libraryItem.setCurrentCustomer(customer);
            customer.addItem(libraryItem);
            return true;
        } else {
            return false;
        }
    }

    public List<LibraryItem> getAvailableItemsByType(Class<? extends LibraryItem> type){
        List<LibraryItem> items = new ArrayList<LibraryItem>();
        for (LibraryItem libraryItem : libraryItems){
            if (libraryItem.getClass().getName().equals(type.getName()) && libraryItem.isAvailable() )
                items.add(libraryItem);
        }
        return items;
    }

    public void addCustomer (Customer customer){
        this.customers.add(customer);
    }

    public List<Customer> getCustomers(){
        return this.customers;
    }

    public boolean returnItem(Customer customer, LibraryItem libraryItem){
        if (!verifyCustomerAndItem(customer, libraryItem))
            return false;

        if (customer.haveItem(libraryItem)){
            customer.removeItem(libraryItem);
            libraryItem.removeCurrentCustomer();
            return true;
        }
        return false;
    }

    public LibraryItem getItem(int id){
        for (LibraryItem libraryItem : libraryItems){
            if (libraryItem.getId() == id){
                return libraryItem;
            }
        }
        return null;
    }

    private boolean verifyCustomerAndItem(Customer customer, LibraryItem libraryItem) {
        return (customer != null && libraryItem != null);
    }

}
